<template>
	<view class="container">
		<view class="list">
			<view class="item" v-for="(item,index) in list" :key="index" :item-id="index" :data-skuid="item.skuId">
				<view class="flex-box">
					<view class="select-icon" @click="switchSelect(index, !item.isSelect);" :data-index="index">
						<image :src="item.isSelect?'../../static/images/select.png':'../../static/images/select-no.png'"
							mode="widthFix"></image>
					</view>
					<view class="img" @click="goDetail(item)"
						:style="{background:item.skuThumbnail?('url('+baseUrl + item.skuThumbnail +') center no-repeat'):'',backgroundSize:'cover'}">
					</view>
					<view class="text-box">
						<view class="name" @click="goDetail(item)">
							{{item.skuName}}
						</view>
						<view class="kg">
							重量：1.07G
						</view>
						<view class="price">
							¥{{item.price}}
						</view>
					</view>

				</view>

				<view class="num-box">
					<view @click="minusCount" :data-index="index" class="cut">
						<image :src="item.qty<=1?'../../static/images/icon-cut.png':'../../static/images/icon-cut1.png'"
							mode="widthFix"></image>
					</view>
					<view class="num">{{item.qty}}</view>
					<view @click="addCount" :data-index="index" class="add">
						<image src="../../static/images/icon-add.png" mode="widthFix"></image>
					</view>
				</view>
			</view>
		</view>

		<view class="bottom">
			<view class="all-select">
				<view class="left" @click="allSelect">
					<image :src="isAllSelect?'../../static/images/select.png':'../../static/images/select-no.png'"
						mode="widthFix"></image>
					全选
				</view>
				<view class="right" @click="editbtn">
					批量删除
				</view>
			</view>
			<view class="column" v-if="!edit">
				<view class="left">
					已选（{{selectNum}}）
				</view>
				<view class="right">
					<view class="text">
						<text>合计</text>
						<text class="price">¥{{totalMoney}}</text>
						<view class="tips">免配送费</view>
					</view>
					<view class="buy-btn" @click="toBuy">去结算</view>
				</view>
			</view>

			<view class="column" v-if="edit">
				<view class="left">
					已选（{{selectNum}}）
				</view>
				<view class="right">

					<view class="buy-btn" @click="delbtn">删除</view>
				</view>
			</view>


		</view>
	</view>
</template>

<script>
	import {
		getCart,
		removeCart,
		modifyCart
	} from '@/api/cart.js';
	export default {
		data() {
			return {
				baseUrl: this.$baseUrl,
				list: [],
				isAllSelect: false,
				totalMoney: 0.00,
				edit: false,
				selectNum: 0,
				selectid: '',
				cartItemId: '',
				selectedId: []
			}
		},
		onLoad() {
			// this.init();
		},
		onHide() {
			// uni.setStorageSync('selectid', '')
			// uni.setStorageSync('cartItemId', '')
		},
		onShareAppMessage(e) {
			console.log(e, 1111111)
			let mpShare={
				title:'久福到家',
				path:'/pages/index/index?scene='
			}
			
			if(uni.getStorageSync('inviteId')){
				let inviteId=uni.getStorageSync('inviteId')
				mpShare.path='/pages/index/index?scene='+inviteId
			}
			return mpShare
		},
		onShow() {
			this.init();
			this.cartItemId = '';
			this.selectid = '';
			this.selectNum = 0;
			this.isAllSelect = false;
			this.totalMoney = 0.00;
		},
		methods: {
			init() {
				this.selectedId = []
				getCart().then(res => {
					console.log(res)
					if(res.data.cartItems==undefined){
						this.list = []
						this.selectid = '';
						this.selectNum = 0;
						this.isAllSelect = false;
						this.totalMoney = 0.00;
						console.log(1111)
					}else{
						this.list = res.data.cartItems
						this.list.forEach(item => {
							this.$set(item, 'isSelect', false)
						})
					}
					if(uni.getStorageSync('cartItemId') && uni.getStorageSync('cartItemId') !== '') {
						let arr = uni.getStorageSync('cartItemId').split(',')
						arr.forEach((r) => {
							this.list.forEach((item, index) => {
								if(item.id == r) {
									item.isSelect = true
									this.switchSelect(index, true)
								}
							})
						})
					}
				})
			},
			goDetail(item) {
				uni.navigateTo({
					url: '/pages/allgoods/details?pid=' + item.productId
				})
			},
			editbtn() {
				this.edit = !this.edit
			},
			
			modify(item) {
				modifyCart({skuId: item.skuId, quantity: item.qty}).then(res => {
					// uni.setStorageSync('selectList', this.selectList)
					// this.selectList = []
					this.init()
				})
			},

			// 单选
			switchSelect(index, flag) {
				// var index = e.currentTarget.dataset.index;
				this.list[index].isSelect = flag
				//价钱统计
				if (this.list[index].isSelect) {
					// this.totalMoney = (parseFloat(this.totalMoney) + parseFloat(this.list[index].price * this.list[index].qty)).toFixed(2);
					if(this.cartItemId.indexOf(this.list[index].id) === -1) {
						this.selectNum += 1
						this.selectid += this.list[index].skuId + ",";
						this.cartItemId += this.list[index].id + ",";
					}
				} else {
					// this.totalMoney = (parseFloat(this.totalMoney) - parseFloat(this.list[index].price * this.list[index].qty)).toFixed(2);
					this.selectid = this.selectid.replace(this.list[index].skuId + ",", ""),
					this.cartItemId = this.cartItemId.replace(this.list[index].id + ",", "")
					this.selectNum -= 1
				}
				this.countTotal()
				//判断是否全选
				// let Allprice = 0
				// for (let i = 0; i < this.list.length; i++) {
				// 	Allprice = (parseFloat(Allprice) + parseFloat(this.list[i].price * this.list[i].qty)).toFixed(2)
				// }
				// if (Allprice == this.totalMoney) {
				// 	this.isAllSelect = true;
				// } else {
				// 	this.isAllSelect = false;
				// }
				if (this.selectNum == this.list.length) {
					this.isAllSelect = true;
				} else {
					this.isAllSelect = false;
				}
				
				uni.setStorageSync('selectid', this.selectid)
				uni.setStorageSync('cartItemId', this.cartItemId)
			},
			countTotal() {
				let sum = 0
				this.list.forEach(r => {
					if(r.isSelect) {
						sum += parseFloat((r.price * r.qty).toFixed(2))
					}
				})
				this.totalMoney = sum
			},
			//全选
			allSelect(e) {
				//处理全选逻辑
				if (!this.isAllSelect) {
					this.totalMoney = 0;
					this.selectid = '';
					this.cartItemId = ''
					for (var i = 0; i < this.list.length; i++) {
						this.list[i].isSelect = true;
						this.totalMoney = (parseFloat(this.totalMoney) + parseFloat(this.list[i].price * this.list[i].qty)).toFixed(2)
						this.selectNum = this.list.length;
						this.selectid += this.list[i].skuId + ",";
						this.cartItemId += this.list[i].id + ",";
					}
					// this.countTotal()
				} else {
					for (var i = 0; i < this.list.length; i++) {
						this.list[i].isSelect = false;
						this.totalMoney = 0;
						this.selectNum = 0;
						this.selectid = '';
						this.cartItemId = ''
					}
				}
				this.isAllSelect = !this.isAllSelect
				
				uni.setStorageSync('selectid', this.selectid)
				uni.setStorageSync('cartItemId', this.cartItemId)
			},

			// 增加数量
			addCount(e) {
				var index = e.currentTarget.dataset.index;
				var list = this.list;
				var num = list[index].qty;
				num = num + 1;
				this.list[index].qty = num
				this.modify(this.list[index])
				this.getTotalPrice();
			},
			// 减少数量
			minusCount(e) {
				var index = e.currentTarget.dataset.index;
				var list = this.list;
				var num = list[index].qty;
				if (num <= 1) {
					return false;
				}
				num = num - 1;
				this.list[index].qty = num
				this.modify(this.list[index])
				this.getTotalPrice()
			},

			getTotalPrice() {
				var list = this.list; // 获取购物车列表
				var total = 0;
				for (let i = 0; i < list.length; i++) { // 循环列表得到每个数据
					if (list[i].isSelect) { // 判断选中才会计算价格
						total += list[i].qty * list[i].price; // 所有价格加起来
					}
				}
				this.list = list,
					this.totalMoney = total.toFixed(2)
			},

			delbtn() {
				removeCart({
					skuIds: this.selectid
				}).then(res => {
					console.log(res)
					this.init();
					this.selectNum = 0;
					this.totalMoney = 0.00;
					this.edit=false;
				})
			},
			toBuy() {
				let id = this.cartItemId
				console.log(id)
				if (id == '') {
					uni.showToast({
						title: '请先选择商品',
						icon: 'none'
					})
				} else {
					uni.navigateTo({
						url: '/pages/pay/pay?id=' + id

					})
				}

			}

		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f5f5f5;
	}

	.container {
		.list {
			padding: 30rpx 0;

			.item {
				width: 100%;
				background-color: #fff;
				padding: 30rpx;
				margin-bottom: 20rpx;

				.flex-box {
					display: flex;
					align-items: center;
					margin-bottom: 10rpx;

					.select-icon {
						width: 34rpx;
					}

					.img {
						width: 160rpx;
						height: 160rpx;
						background-color: #f5f5f5 !important;
						margin: 0 20rpx;
					}

					.text-box {
						.name {
							font-size: 24rpx;
							margin-bottom: 20rpx;
						}

						.kg {
							padding: 12rpx 13rpx;
							background-color: #f6f6f6;
							margin-bottom: 35rpx;
							color: #898989;
							font-size: 28rpx;
						}

						.price {
							color: #b81c22;
							font-size: 24rpx;
						}
					}

				}

				.num-box {
					display: flex;
					align-items: center;
					justify-content: flex-end;

					view {
						width: 50rpx;
						height: 50rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						border: solid 1px #eeeeee;
						font-size: 28rpx;

						image {
							width: 16rpx;
						}
					}

					.num {
						width: 70rpx;
						border-left: none;
						border-right: none;
					}
				}


				.num-box .cut.nocut {
					color: #dddddd;
				}

			}


		}

		.bottom {
			// position: fixed;
			width: 100%;
			bottom: 0;
			left: 0;
			padding: 0 30rpx;

			.all-select {
				display: flex;
				align-items: center;
				justify-content: space-between;
				height: 90rpx;
				color: #595757;
				font-size: 24rpx;
				border-bottom: 1px solid #f1f1f1;

				.left {
					display: flex;
					align-items: center;

					image {
						width: 34rpx;
						margin-right: 20rpx;
					}

				}
			}

			.column {
				display: flex;
				align-items: center;
				justify-content: space-between;
				height: 140rpx;

				.left {
					color: #595757;
					font-size: 28rpx;
				}

				.right {
					display: flex;
					align-items: center;

					.text {
						margin-right: 20rpx;

						text {
							font-size: 24rpx;
							color: #333333;
							vertical-align: middle;
						}

						.price {
							margin-left: 10rpx;
							font-size: 32rpx;
							font-weight: 500;
							color: #b81c22;
						}


						.tips {
							margin-top: 15rpx;
							font-size: 18rpx;
							color: #999999;
							text-align: right;
						}
					}

					.buy-btn {
						width: 240rpx;
						height: 80rpx;
						line-height: 80rpx;
						text-align: center;
						color: #fff;
						letter-spacing: 4rpx;
						font-size: 24rpx;
						background-color: #b81c22;
					}
				}
			}
		}
	}
</style>
